﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using static SuperKit.CommandReader;
using static System.Net.Mime.MediaTypeNames;

namespace SuperKit
{
    /// <summary>
    /// GalleryWindow.xaml 的交互逻辑
    /// </summary>
    public partial class GalleryWindow : Window {
        protected static int STATE_NORMAL = 0;
        protected static int STATE_CHECKED = 1;
        protected static int MAX_LOAD = 100;

        public string DirPath { get; set; }
        private ConfigReader Cfg => ConfigReader.Instance;
        public List<FileInfo> Files { get; set; }
        public GalleryManager Ctrler { get; set; }
        private GalleryLoader _loader;
        private DirectoryInfo[] fastDirs;

        public string FileHeader { get; set; }

        public GalleryWindow() {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e) {
            InitThumbSize();
            SetupCatalog();

            Ctrler = new GalleryManager(this, listFiles, headerFile, txtAddition, txtRename);
            Ctrler.SetupRename(buttonRename, buttonBatchRename);
            Ctrler.Load(DirPath);

            listGallery.KeyDown += ListGallery_KeyDown;
        }

        private void ListGallery_KeyDown(object sender, KeyEventArgs e) {
            if ((int)e.Key >= (int)Key.D1 && (int)e.Key <= (int)Key.D9) {
                e.Handled = true;
                int number = e.Key - Key.D1;
                var dir = Kit.SafeGet(fastDirs, number);
                MoveToFastImageCatalog(dir);
                //MessageBox.Show($"Num:{number}, Dir:{dir.Name}");
            }
        }
        private void SetupCatalog() {
            // 得到目录，这里面Mark和Catalog都会用到
            var catalog_list = Cfg.Catalog.Split(Kit.CATALOG_SPLIT);

            // 配置Catalog
            menu_Catalog.Items.Clear();
            int index = 0;
            foreach (var i in catalog_list) {
                var header = i.Length > 24 ? (i[..24] + "...") : i;
                MenuItem item = new() { Header = header, Tag = index };
                item.IsChecked = index == Cfg.CatalogIndex;
                menu_Catalog.Items.Add(item);
                item.Click += Catalog_Click;
                index++;
            }

            // 配置Mark
            menu_Mark.Items.Clear();
            index = 0;
            foreach (var i in catalog_list) {
                var header = i.Length > 24 ? (i[..24] + "...") : i;
                MenuItem item = new() { Header = header, Tag = index };
                item.IsChecked = index == Cfg.MarkIndex;
                menu_Mark.Items.Add(item);
                item.Click += Mark_Click;
                index++;
            }

            // 配置快速Catalog
            var arr = Cfg.CatalogArray;
            menu_Fast_Catalog.Items.Clear();
            foreach (var text in arr) {
                MenuItem item = new() { Header = text };
                menu_Fast_Catalog.Items.Add(item);
                item.Click += (o, e) => {
                    Ctrler.SetState(text);
                };
            }

            // 配置ToolBar的快速Catalog
            toolbar_Catalog.Items.Clear();

            // 依次加入列表
            foreach (var text in arr) {
                Button item = new() { Content = text };
                toolbar_Catalog.Items.Add(item);
                item.Click += (o, e) => {
                    Ctrler.SetState(text);
                };
            }

            // 配置快速Mark
            arr = Cfg.MarkArray;
            menu_Prefix.Items.Clear();
            menu_Suffix.Items.Clear();
            toolbar_Suffix.Items.Clear();

            foreach (var text in arr) {
                MenuItem item = new() { Header = text };
                menu_Prefix.Items.Add(item);
                item.Click += (o, e) => {
                    txtAddition.Text = text;
                    Ctrler.AddAddition(text, true);
                };
            }

            // 配置快速图片分类
            toolbar_ImageCatalog.Items.Clear();
            DirectoryInfo dir = new DirectoryInfo(Cfg.FastImageCatalog);
            if (!dir.Exists) {
                dir = new DirectoryInfo(DirPath);
            }
            fastDirs = dir.GetDirectories();
            Array.Sort(fastDirs, (a, b) => { return a.Name.CompareTo(b.Name); });


            foreach (var i in fastDirs) {
                Button item = new() { Content = i.Name };
                toolbar_ImageCatalog.Items.Add(item);
                item.Click += (o, e) => {
                    MoveToFastImageCatalog(i);
                    //Ctrler.SetState(text);
                };
            }

            // 这里有一个特殊的项目，是增加星标的
            Button itemStar = new() { Content = "(★)" };
            toolbar_Suffix.Items.Add(itemStar);
            itemStar.Click += (o, e) => {
                Ctrler.SetFavorStar();
            };

            foreach (var text in arr) {
                MenuItem item = new() { Header = text };
                menu_Suffix.Items.Add(item);
                item.Click += (o, e) => {
                    txtAddition.Text = text;
                    Ctrler.AddAddition(text, false);
                };

                Button btn = new() { Content = text };
                toolbar_Suffix.Items.Add(btn);
                btn.Click += (o, e) => {
                    txtAddition.Text = text;
                    Ctrler.AddAddition(text, false);
                };
            }
            
        }

        private void MoveToFastImageCatalog(DirectoryInfo dir) {
            string s = "";
            List<GalleryBean> list = new List<GalleryBean>();
            foreach (var i in listGallery.SelectedItems) {
                var bean = i as GalleryBean;
                s += bean.FullName + ",";
                var newPath = Path.Combine(dir.FullName, bean.Name);
                newPath = Kit.GetNonExistName(newPath);
                File.Move(bean.FullName, newPath);
                list.Add(bean);
                
            }

            int selectedIndex = listGallery.SelectedIndex;

            foreach (var i in list) {
                _loader.Items.Remove(i);
                //Ctrler.Items.Remove(i);
            }                        

            listGallery.SelectedIndex = selectedIndex;
            
            
            return;
        }

        private void Catalog_Click(object sender, System.Windows.RoutedEventArgs e) {
            MenuItem item = sender as MenuItem;
            int index = (int)item.Tag;
            Cfg.CatalogIndex = index;
            Cfg.Save();
            SetupCatalog();
        }

        private void Mark_Click(object sender, System.Windows.RoutedEventArgs e) {
            MenuItem item = sender as MenuItem;
            int index = (int)item.Tag;
            Cfg.MarkIndex = index;
            Cfg.Save();
            SetupCatalog();
        }

        private void OpenMain_Click(object sender, RoutedEventArgs e) {
            MainWindow mainWindow = new MainWindow();
            mainWindow.Show();
        }

        private void Settings_Click(object sender, RoutedEventArgs e) {
            SettingsWindow settingsWindow = new SettingsWindow();
            settingsWindow.ShowDialog();
        }

        private void Exit_Click(object sender, RoutedEventArgs e) {
            Close();
        }





        private void InitThumbSize() {
            string size = Cfg.GetString("ThumbSize");
            menu_Size.Items.Clear();
            var arr = Cfg.GetStringArray("ThumbPreset");
            foreach (var i in arr) {
                MenuItem item = new() { Header = i };
                menu_Size.Items.Add(item);
                item.Click += (o, e) => {
                    ChangeImageSize(Kit.TextToSize(i));
                };
                item.Icon = App.CheckIcon(Kit.IsEqual(size, i));
            }
        }

        private void ChangeImageSize(System.Drawing.Size size) {
            Cfg.SetValue("ThumbSize", $"{size.Width}x{size.Height}");
            Cfg.Save();
            LoadImages(CurrentPath);
            InitThumbSize();

        }

        private Size ThumbSize {
            get {
                var size = Kit.TextToSize(Cfg.GetString("ThumbSize"));
                return new Size(size.Width, size.Height);
            }
        }


        //private void listViewDirs_SelectedIndexChanged(object sender, EventArgs e) {
        //    if (listFiles.SelectedItems.Count == 0 || Ctrler.LockRefresh) {
        //        return;
        //    }

        //    GalleryItem dir = Ctrler.Get(listFiles.SelectedIndex);
        //    LoadImages(dir.FullName);
        //}

        private string CurrentPath { get; set; }

        private void LoadImages(string path) {
            if (path == null) {
                return;
            }

            CurrentPath = path;

            Files = Kit.GetAllFiles(null, new DirectoryInfo(path), Kit.IMG_EXTS);

            //listGallery.Bind(Files, ThumbSize);
        }



        private void listBoxDir_MouseDoubleClick(object sender, MouseEventArgs e) {
            Ctrler.ToggleState();
        }

        //private void listBoxDir_KeyPress(object sender, KeyPressEventArgs e) {
        //    Ctrler.HandleKey(sender, e);
        //}



        private void buttonExecute_Click(object sender, EventArgs e) {
            Ctrler.ExecuteSelection();
        }

        private void buttonFastCombine_Click(object sender, EventArgs e) {
            Ctrler.ExecuteFastCombine();
        }

        protected void Log(string str) {
            Title = str;
        }

        private void buttonFavorStar_Click(object sender, EventArgs e) {
            Ctrler.SetFavorStar();
        }
                

        private void listFiles_DoubleClick(object sender, EventArgs e) {
            Ctrler.ToggleState();
        }


        private void buttonDeleteImage_Click(object sender, EventArgs e) {
            DeleteSelected();
        }

        private void DeleteSelected() {
            foreach (var item in listGallery.SelectedItems) {
                //File.Delete(item.file.FullName);
            }

            LoadImages(CurrentPath);
            Kit.Beep();
        }

        private void listFiles_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            var item =  listFiles.SelectedItem as GalleryFileViewModel;
            if (item == null) {
                return;
            }

            // 处理文件名的编辑
            txtRename.Text = item.Name;
            Ctrler.CurrentItem = item;

            if (item == null || item.IsDirectory == false) {
                return;
            }
            // 已经处于项目之中，不需要重复加载
            if (_loader != null && Kit.IsEqual(_loader.CurrentPath, item.FullName)) {
                return;
            }
            LoadGallery(item.FullName);
        }

        private void LoadGallery(string fullName) {
            // 如果已经有项目，中断
            if (_loader != null) {
                _loader.Close();
            }
            _loader = new GalleryLoader(fullName);
            listGallery.ItemsSource = _loader.Load();
            Title = $"图像浏览器 - {_loader.Items.Count} 文件";
            // 将显示区域移动到最上
            if (listGallery.Items.Count > 0) {
                listGallery.ScrollIntoView(listGallery.Items[0]);
            }
            
        }

        public void CancelLoad() {
            if (_loader != null) {
                _loader.Close();
                _loader = null;
            }
        }

        private void Execute_Catalog_Click(object sender, RoutedEventArgs e) {
            Ctrler.ExecuteSelection();
        }

        private void AddStar_Click(object sender, RoutedEventArgs e) {
            Ctrler.SetFavorStar();
        }

        private void Delete_Click(object sender, RoutedEventArgs e) {
            // 没有载入项目时，不处理.
            if (_loader == null) {
                return;
            }

            foreach (var i in listGallery.SelectedItems) {
                var item = i as GalleryBean;
                RemoveToTrash(item.FullName);
                item.IsDiscard = true;
            }
            // 重新载入
            //LoadGallery(_loader.CurrentPath);
            _loader.RemoveDiscard();
        }

        private void RemoveToTrash(string fullName) {
            FileInfo info = new FileInfo(fullName);
            // 在当前的项目中建立一个Trash目录
            var trashPath = Path.Combine(DirPath, "(_Trash)", info.Directory.Name);
            if (Directory.Exists(trashPath) == false) {
                Directory.CreateDirectory(trashPath);
            }
            // 将项目移动到Trash
            var newPath = Path.Combine(trashPath, info.Name);
            File.Move(info.FullName, newPath);
            
        }

        private void Gallery_KeyDown(object sender, KeyEventArgs e) {
            if (e.Key == Key.Delete) {
                Delete_Click(null, null);
            }
        }

        public void Combine_Click(object sender, RoutedEventArgs e) {
            if (listFiles.SelectedItems.Count == 0) {
                return;
            }

            CombineWindow combineWindow = new CombineWindow();
            foreach (var i in listFiles.SelectedItems) {
                var item = i as GalleryFileViewModel;
                combineWindow.Add(item.FullName);
            }

            if (combineWindow.ShowDialog() == true) {
                Ctrler.Reload();
            }
        }
    }
}
